<template>
  <div class="host-import-export">
    <!-- 导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入主机"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <!-- 步骤指示器 -->
        <el-steps :active="importStep" finish-status="success">
          <el-step title="选择文件" />
          <el-step title="数据预览" />
          <el-step title="导入结果" />
        </el-steps>

        <!-- 步骤1: 文件选择 -->
        <div v-if="importStep === 0" class="step-content">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls,.csv"
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 Excel (.xlsx, .xls) 和 CSV (.csv) 格式文件
              </div>
            </template>
          </el-upload>

          <el-divider>或</el-divider>

          <div class="template-download">
            <p>下载导入模板：</p>
            <el-button @click="downloadTemplate('excel')" type="primary">
              <el-icon><Download /></el-icon>
              Excel模板
            </el-button>
            <el-button @click="downloadTemplate('csv')" type="success">
              <el-icon><Download /></el-icon>
              CSV模板
            </el-button>
          </div>

          <div class="import-rules">
            <h4>导入规则说明：</h4>
            <ul>
              <li>主机名和IP地址为必填字段</li>
              <li>IP地址必须唯一</li>
              <li>环境和主机类型必须已存在</li>
              <li>SSH端口默认为22</li>
              <li>支持最多1000条记录</li>
            </ul>
          </div>
        </div>

        <!-- 步骤2: 数据预览 -->
        <div v-if="importStep === 1" class="step-content">
          <div class="preview-summary">
            <el-alert
              :title="`共解析到 ${previewData.length} 条记录，其中 ${validRecords} 条有效，${invalidRecords} 条无效`"
              type="info"
              show-icon
              :closable="false"
            />
          </div>

          <el-table 
            :data="previewData" 
            max-height="400"
            style="margin-top: 20px;"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="hostname" label="主机名" width="150" />
            <el-table-column prop="ip" label="IP地址" width="120" />
            <el-table-column prop="environment" label="环境" width="100" />
            <el-table-column prop="host_type" label="主机类型" width="100" />
            <el-table-column prop="ssh_port" label="SSH端口" width="80" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.valid ? 'success' : 'danger'">
                  {{ row.valid ? '有效' : '无效' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="error" label="错误信息" min-width="200">
              <template #default="{ row }">
                <span v-if="!row.valid" class="error-text">{{ row.error }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 步骤3: 导入结果 -->
        <div v-if="importStep === 2" class="step-content">
          <div class="import-result">
            <el-result
              :icon="importResult.success ? 'success' : 'error'"
              :title="importResult.title"
              :sub-title="importResult.message"
            >
              <template #extra>
                <div class="result-stats">
                  <el-statistic
                    title="成功导入"
                    :value="importResult.successCount"
                    suffix="条"
                  />
                  <el-statistic
                    title="导入失败"
                    :value="importResult.failureCount"
                    suffix="条"
                  />
                </div>
              </template>
            </el-result>

            <div v-if="importResult.errors.length > 0" class="error-details">
              <h4>失败详情：</h4>
              <el-table :data="importResult.errors" max-height="200">
                <el-table-column prop="row" label="行号" width="80" />
                <el-table-column prop="hostname" label="主机名" width="150" />
                <el-table-column prop="error" label="错误原因" />
              </el-table>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button 
            v-if="importStep > 0" 
            @click="prevStep"
          >
            上一步
          </el-button>
          <el-button 
            v-if="importStep === 0" 
            type="primary" 
            @click="nextStep"
            :disabled="!selectedFile"
          >
            下一步
          </el-button>
          <el-button 
            v-if="importStep === 1" 
            type="primary" 
            @click="startImport"
            :loading="importing"
            :disabled="validRecords === 0"
          >
            开始导入
          </el-button>
          <el-button 
            v-if="importStep === 2" 
            type="primary" 
            @click="finishImport"
          >
            完成
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog
      v-model="showExportDialog"
      title="导出主机列表"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel格式</el-radio>
            <el-radio label="csv">CSV格式</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="导出范围">
          <el-radio-group v-model="exportForm.scope">
            <el-radio label="all">全部主机</el-radio>
            <el-radio label="filtered">当前筛选结果</el-radio>
            <el-radio label="selected">选中的主机</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="包含字段">
          <el-checkbox-group v-model="exportForm.fields">
            <el-checkbox label="hostname">主机名</el-checkbox>
            <el-checkbox label="ip">IP地址</el-checkbox>
            <el-checkbox label="environment">环境</el-checkbox>
            <el-checkbox label="host_type">主机类型</el-checkbox>
            <el-checkbox label="status">状态</el-checkbox>
            <el-checkbox label="ssh_port">SSH端口</el-checkbox>
            <el-checkbox label="description">描述</el-checkbox>
            <el-checkbox label="created_at">创建时间</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showExportDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="startExport"
          :loading="exporting"
        >
          开始导出
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import { cmdbApi } from '@/api/monitoring'

// Props
interface Props {
  selectedHosts?: any[]
  filterParams?: any
}

const props = withDefaults(defineProps<Props>(), {
  selectedHosts: () => [],
  filterParams: () => ({})
})

// Emits
const emit = defineEmits(['import-success', 'export-success'])

// 响应式数据
const showImportDialog = ref(false)
const showExportDialog = ref(false)
const importStep = ref(0)
const importing = ref(false)
const exporting = ref(false)
const selectedFile = ref(null)
const previewData = ref([])
const uploadRef = ref()

// 导入结果
const importResult = reactive({
  success: false,
  title: '',
  message: '',
  successCount: 0,
  failureCount: 0,
  errors: []
})

// 导出表单
const exportForm = reactive({
  format: 'excel',
  scope: 'all',
  fields: ['hostname', 'ip', 'environment', 'host_type', 'status']
})

// 计算属性
const validRecords = computed(() => {
  return previewData.value.filter(item => item.valid).length
})

const invalidRecords = computed(() => {
  return previewData.value.filter(item => !item.valid).length
})

// 显示导入对话框
const showImport = () => {
  showImportDialog.value = true
  resetImport()
}

// 显示导出对话框
const showExport = () => {
  showExportDialog.value = true
}

// 重置导入状态
const resetImport = () => {
  importStep.value = 0
  selectedFile.value = null
  previewData.value = []
  importing.value = false
  Object.assign(importResult, {
    success: false,
    title: '',
    message: '',
    successCount: 0,
    failureCount: 0,
    errors: []
  })
}

// 文件选择处理
const handleFileChange = (file: any) => {
  selectedFile.value = file
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isValidType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                     file.type === 'application/vnd.ms-excel' ||
                     file.type === 'text/csv'
  
  if (!isValidType) {
    ElMessage.error('只支持 Excel 和 CSV 格式文件')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }
  
  return false // 阻止自动上传
}

// 下载模板
const downloadTemplate = (format: string) => {
  const templateData = [
    {
      '主机名': 'web-server-01',
      'IP地址': '192.168.1.100',
      '环境': '生产环境',
      '主机类型': 'Web服务器',
      'SSH端口': 22,
      'SSH用户名': 'root',
      '描述': 'Web服务器示例'
    }
  ]
  
  if (format === 'excel') {
    const ws = XLSX.utils.json_to_sheet(templateData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '主机导入模板')
    XLSX.writeFile(wb, '主机导入模板.xlsx')
  } else {
    // CSV导出逻辑
    const csvContent = convertToCSV(templateData)
    downloadCSV(csvContent, '主机导入模板.csv')
  }
  
  ElMessage.success('模板下载成功')
}

// 下一步
const nextStep = () => {
  if (importStep.value === 0 && selectedFile.value) {
    parseFile()
  }
}

// 上一步
const prevStep = () => {
  if (importStep.value > 0) {
    importStep.value--
  }
}

// 解析文件
const parseFile = async () => {
  try {
    const file = selectedFile.value.raw
    const data = await readFile(file)
    
    // 验证数据
    const validatedData = validateData(data)
    previewData.value = validatedData
    
    importStep.value = 1
  } catch (error) {
    ElMessage.error('文件解析失败: ' + error.message)
  }
}

// 读取文件
const readFile = (file: File): Promise<any[]> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const data = e.target?.result
        let jsonData = []
        
        if (file.type === 'text/csv') {
          // CSV解析
          jsonData = parseCSV(data as string)
        } else {
          // Excel解析
          const workbook = XLSX.read(data, { type: 'binary' })
          const sheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[sheetName]
          jsonData = XLSX.utils.sheet_to_json(worksheet)
        }
        
        resolve(jsonData)
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => reject(new Error('文件读取失败'))
    
    if (file.type === 'text/csv') {
      reader.readAsText(file)
    } else {
      reader.readAsBinaryString(file)
    }
  })
}

// 验证数据
const validateData = (data: any[]) => {
  return data.map((item, index) => {
    const errors = []
    
    // 必填字段验证
    if (!item['主机名'] && !item.hostname) {
      errors.push('主机名不能为空')
    }
    
    if (!item['IP地址'] && !item.ip) {
      errors.push('IP地址不能为空')
    }
    
    // IP格式验证
    const ip = item['IP地址'] || item.ip
    if (ip && !isValidIP(ip)) {
      errors.push('IP地址格式不正确')
    }
    
    return {
      hostname: item['主机名'] || item.hostname,
      ip: item['IP地址'] || item.ip,
      environment: item['环境'] || item.environment,
      host_type: item['主机类型'] || item.host_type,
      ssh_port: item['SSH端口'] || item.ssh_port || 22,
      ssh_username: item['SSH用户名'] || item.ssh_username || 'root',
      description: item['描述'] || item.description,
      valid: errors.length === 0,
      error: errors.join(', ')
    }
  })
}

// IP地址验证
const isValidIP = (ip: string) => {
  const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/
  return ipRegex.test(ip)
}

// 开始导入
const startImport = async () => {
  try {
    importing.value = true
    
    const validData = previewData.value.filter(item => item.valid)
    const response = await cmdbApi.batchImportHosts(validData)
    
    if (response.data.success) {
      importResult.success = true
      importResult.title = '导入成功'
      importResult.message = `成功导入 ${response.data.data.successCount} 条记录`
      importResult.successCount = response.data.data.successCount
      importResult.failureCount = response.data.data.failureCount
      importResult.errors = response.data.data.errors || []
    } else {
      throw new Error(response.data.message)
    }
  } catch (error) {
    importResult.success = false
    importResult.title = '导入失败'
    importResult.message = error.message
  } finally {
    importing.value = false
    importStep.value = 2
  }
}

// 完成导入
const finishImport = () => {
  showImportDialog.value = false
  emit('import-success')
}

// 开始导出
const startExport = async () => {
  try {
    exporting.value = true
    
    let params = {}
    
    if (exportForm.scope === 'filtered') {
      params = props.filterParams
    } else if (exportForm.scope === 'selected') {
      params = { ids: props.selectedHosts.map(h => h.id) }
    }
    
    const response = await cmdbApi.exportHosts({
      ...params,
      format: exportForm.format,
      fields: exportForm.fields
    })
    
    if (response.data.success) {
      // 下载文件
      const blob = new Blob([response.data.data], { 
        type: exportForm.format === 'excel' ? 
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : 
          'text/csv'
      })
      
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `主机列表.${exportForm.format === 'excel' ? 'xlsx' : 'csv'}`
      link.click()
      window.URL.revokeObjectURL(url)
      
      ElMessage.success('导出成功')
      showExportDialog.value = false
      emit('export-success')
    }
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  } finally {
    exporting.value = false
  }
}

// 工具函数
const parseCSV = (csvText: string) => {
  const lines = csvText.split('\n')
  const headers = lines[0].split(',')
  const data = []
  
  for (let i = 1; i < lines.length; i++) {
    if (lines[i].trim()) {
      const values = lines[i].split(',')
      const obj = {}
      headers.forEach((header, index) => {
        obj[header.trim()] = values[index]?.trim()
      })
      data.push(obj)
    }
  }
  
  return data
}

const convertToCSV = (data: any[]) => {
  if (data.length === 0) return ''
  
  const headers = Object.keys(data[0])
  const csvContent = [
    headers.join(','),
    ...data.map(row => headers.map(header => row[header]).join(','))
  ].join('\n')
  
  return csvContent
}

const downloadCSV = (content: string, filename: string) => {
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename
  link.click()
  URL.revokeObjectURL(link.href)
}

// 暴露方法
defineExpose({
  showImport,
  showExport
})
</script>

<style scoped>
.step-content {
  margin: 20px 0;
  min-height: 300px;
}

.template-download {
  text-align: center;
  margin: 20px 0;
}

.import-rules {
  margin-top: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}

.import-rules h4 {
  margin-top: 0;
  color: #606266;
}

.import-rules ul {
  margin: 10px 0;
  padding-left: 20px;
}

.import-rules li {
  margin: 5px 0;
  color: #909399;
}

.preview-summary {
  margin-bottom: 20px;
}

.error-text {
  color: #F56C6C;
  font-size: 12px;
}

.import-result {
  text-align: center;
}

.result-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin: 20px 0;
}

.error-details {
  margin-top: 30px;
  text-align: left;
}

.error-details h4 {
  color: #F56C6C;
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}
</style>
